package com.taniurakengo.sourceviewer;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.taniurakengo.sourceviewer.R;

import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 
 * @author Taniura
 *
 */
public class FileBrowserActivity extends ListActivity {

	private String currentPath;

    /**
     * 
     */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filebrowser_activity);
		
		try {
			this.setMyList();
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}

	}

	/**
	 * 
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.filebrowser_menu, menu);
		return true;
	}

	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
        switch(item.getItemId()) {

        	case R.id.menu_open_folder:
        		
				//open activity
				Intent intent1 = new Intent(this, SourceViewActivity.class);
				intent1.putExtra("CURRENT_PATH", currentPath);
				startActivity(intent1);
        	    	
        		return true;
        		
        	case R.id.menu_setting:
        		
				//open activity
				Intent intent2 = new Intent(this, SettingsPreference.class);
				startActivity(intent2);
        	    	
        		return true;        		
        		
//Next Version Feature        
//	        case R.id.menu_favorite:
//
//	        	item.setIcon(getResources().getDrawable(R.drawable.star_full));
//	        	
//	            return true;
//	            
//	        case R.id.menu_folder:
//	        	
//	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
        }

    }
	
	/**
	 * 
	 */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

		try {
	        MyItem myItem = (MyItem) l.getItemAtPosition(position);
	        this.changePath(currentPath + "/" + myItem.file_name);

		} catch (Exception e) {
			System.out.println(e.toString());
		}
        
    }

    
	/**
	 * 
	 * @param tmpPath
	 */
    private void changePath(String tmpPath){

		try {
	    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
	    	Editor editor = pref.edit();

	    	File file = new File(tmpPath);

	    	if (file.isDirectory()){
	    		currentPath = tmpPath;

	    		editor.putString( "CURRENT_PATH", currentPath );
	    		editor.commit();

	    		this.setMyList();
	    		
	    	}else{
	    		if(file.isFile()){

	    			//open activity
	        		Intent intent = new Intent(this, SourceViewActivity.class);
	        		intent.putExtra("CURRENT_PATH", file.getPath());
	                startActivity(intent);
	    		}
	    	}
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}
    	
    }
    
    /**
     * 
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

		try {
	    	if(keyCode == KeyEvent.KEYCODE_BACK){

	    		//check current path
	    		String[] strs = currentPath.split("/");
	    		String tmp="";
	    		for (int i = 1; i < strs.length-1; i++) {
	    			tmp += "/" + strs[i];
	    		}

	    		//judge root
	    		String[] roots = Environment.getExternalStorageDirectory().getPath().split("/");
	    		if(roots.length<strs.length){
	            	this.changePath(tmp);
	    		}
	    		return false;
	    	}
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}

		return super.onKeyDown(keyCode, event);
    }
    
    
    /**
     * 
     */
    private void setMyList(){

		try {
			
	    	//preference
	    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
	    	currentPath = pref.getString("CURRENT_PATH", "");

	    	//check current path
	    	File file;
			if(currentPath.equals("")){
				file = Environment.getExternalStorageDirectory();
				currentPath = file.getPath();
			}else{
				file = new File(currentPath);
			}

	    	//set title
	    	setTitle(currentPath + "/");

			//get filelist
			String[] fileList = file.list();
			//sort
			Arrays.sort(fileList);

			//make list
	        List<MyItem> items = new ArrayList<MyItem>();
	        Locale locale = Locale.getDefault(); 
	        for(int i=0; i<fileList.length;i++){
	        	
	        	File f = new File(currentPath + "/" + fileList[i]);
	        	
	        	//file make date
	        	Date date = new Date(f.lastModified());
	        	DateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss", locale);

	        	//file？
	        	if(f.isFile()){

	        		// check pref
	        		if(IsEnableExtension(f)){
		                items.add(new MyItem(f.getName(),
           					 format.format(date),
           					 1,
           					 getResources().getColor(R.color.file)));
	        		}
	        		
	        	}else{
	                items.add(new MyItem(f.getName(),
	                		             format.format(date),
	                		             1,
	                		             getResources().getColor(R.color.folder)));
	        	}
	        

	        }
	        
	        //set adapter
	        MyItemAdapter adapter = new MyItemAdapter(
	                this,
	                R.layout.my_list_item,
	                items);
	        setListAdapter(adapter);

			
		} catch (Exception e) {
			System.out.println(e.toString());
		}
    }

    private boolean IsEnableExtension(File file){
    	
    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

    	if(pref.getBoolean("BRUSH_ALL", false)) return true;
    	
		if (pref.getBoolean("BRUSH_C++", false) && (file.getName().endsWith(".c") || file.getName().endsWith(".cpp") || file.getName().endsWith(".cc"))) return true;
		if (pref.getBoolean("BRUSH_C++", false) && (file.getName().endsWith(".m") || file.getName().endsWith(".h"))) return true;
		if (pref.getBoolean("BRUSH_C#", false) && (file.getName().endsWith(".cs"))) return true;
		if (pref.getBoolean("BRUSH_CSS", false) && (file.getName().endsWith(".css"))) return true;
		if (pref.getBoolean("BRUSH_JAVA", false) && (file.getName().endsWith(".java"))) return true;
		if (pref.getBoolean("BRUSH_PERL", false) && (file.getName().endsWith(".pl"))) return true;
		if (pref.getBoolean("BRUSH_PHP", false) && (file.getName().endsWith(".php")) ) return true;
		if (pref.getBoolean("BRUSH_PYTHON", false) && (file.getName().endsWith(".py")) ) return true;
		if (pref.getBoolean("BRUSH_RUBY", false) && (file.getName().endsWith(".rb")) ) return true;
		if (pref.getBoolean("BRUSH_SCALE", false) && (file.getName().endsWith(".scala")) ) return true;
		if (pref.getBoolean("BRUSH_SQL", false) && (file.getName().endsWith(".sql")) ) return true;
		if (pref.getBoolean("BRUSH_VB", false) && (file.getName().endsWith(".vb") || file.getName().endsWith(".bas")) ) return true;
		if (pref.getBoolean("BRUSH_XML", false) && (file.getName().endsWith(".html") || file.getName().endsWith(".htm")) ) return true;
		if (pref.getBoolean("BRUSH_XML", false) && (file.getName().endsWith(".xml") || file.getName().endsWith(".xhtm")) ) return true;
		if (pref.getBoolean("BRUSH_XML", false) && (file.getName().endsWith(".storyboard")) ) return true;
    	
		return false;
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        this.changePath(currentPath);
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }  
    
    /**
     * 
     * @author Taniura
     *
     */
    private class MyItem {
        private String  file_name;
        private String  update_date;
        private int     row_number;
        private int     color;
        
        /**
         * 
         * @param a
         * @param b
         * @param n
         * @param c
         */
        MyItem(String a, String b, int n, int c) {
            this.file_name   = a;
            this.update_date = b;
            this.row_number  = n;
            this.color       = c;
        }
    }
    
    /**
     * 
     * @author Taniura
     *
     */
    private class MyItemAdapter extends ArrayAdapter<MyItem> {
    	//
        private LayoutInflater inflater;
        //
        private int tvId;


        
        /**
         * 
         * @param context
         * @param textViewResourceId
         * @param objects
         */
        public MyItemAdapter(Context context, 
        					 int textViewResourceId,
        					 List<MyItem> objects) {
        	
            super(context, textViewResourceId, objects);
            
    		try {
                this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                this.tvId = textViewResourceId;
    			
    		} catch (Exception e) {
    			System.out.println(e.toString());
    		}

        }

        /**
         * 
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        	
        	//
            View v = convertView;

            try {
            	
            	//
                if (v == null) {
                    v = inflater.inflate(this.tvId, null);
                }
                
                //
                MyItem myitem = super.getItem(position);
                if (myitem != null) {
                    TextView t1 = (TextView)v.findViewById(android.R.id.text1);
                    TextView t2 = (TextView)v.findViewById(android.R.id.text2);
                    t1.setText(myitem.file_name);
                    t1.setTextColor(myitem.color);
                    t2.setText(myitem.update_date);
                }
    			
    		} catch (Exception e) {
    			System.out.println(e.toString());
    		}

            return v;
        }
    }
}
